package org.itstack.demo.design.util;

import java.util.*;

public class TopicRandomUtil {

    /**
     * 乱序Map元素，记录对应答案key
     * @param option 题目
     * @param key    答案
     * @return Topic 乱序前 {A=a., B=b., C=c., D=d.} 乱序后 {A=c., B=d., C=a., D=b.}
     */
    static public Topic random(Map<String, String> option, String key) {
        // 获取map的key的名称
        Set<String> keySet = option.keySet();
        ArrayList<String> keyList = new ArrayList<String>(keySet);
        // 打乱题顺序
        Collections.shuffle(keyList);
        // 乱序后的题目Map集合
        HashMap<String, String> optionNew = new HashMap<String, String>();
        int idx = 0;
        String keyNew = "";
        for (String next : keySet) {
            //获取乱序后的选项
            String randomKey = keyList.get(idx++);
            //判断答案和乱序前选项是否一致
            if (key.equals(next)) {
                //一致则把当前选项赋值成新的答案选项
                keyNew = randomKey;
            }
            //放入乱序后的Map集合中
            optionNew.put(randomKey, option.get(next));
        }
        return new Topic(optionNew, keyNew);
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("A","a");
        map.put("B","b");
        map.put("C","c");
        map.put("D","d");

        String key = "A";

        Topic random = random(map, key);
        System.out.println(random);
    }

}
